package com.looli.srb.sms.controller.api;

import com.looli.common.result.R;
import com.looli.common.result.ResponseEnum;
import com.looli.common.utils.RandomUtils;
import com.looli.common.utils.RegexValidateUtils;
import com.looli.srb.sms.controller.client.CoreUserInfoClient;
import com.looli.srb.sms.service.SmsService;
import com.looli.srb.sms.utils.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.looli.common.exception.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
@Slf4j
@AllArgsConstructor
public class ApiSmsController {

    private SmsService smsService;

    private RedisTemplate<String,String> redisTemplate;

    private CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}.json")
    public R send( @ApiParam(value = "手机号", required = true) @PathVariable String mobile ){
        //MOBILE_NULL_ERROR(-202, "手机号不能为空"),
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //MOBILE_ERROR(-203, "手机号不正确"),
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        //手机号是否注册
        boolean result = coreUserInfoClient.checkMobile(mobile);
        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);

        String code = redisTemplate.opsForValue().get("srb:sms:code:" + mobile);
        if (StringUtils.isEmpty(code)){
            //生成验证码
            code = RandomUtils.getFourBitRandom();
        }

        //组装短信模板参数
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);

        //发送短信
        smsService.send(mobile, SmsProperties.TEMPLATE_CODE, param);

        //将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);
        return R.ok().message("短信发送成功");
    }
}